<template>
  <div class="player">
    <div class="player-content">
      <div class="player-info" @click="showPlayerDetail">
        <div class="song-cover">
          <img 
            :src="playerStore.currentSong?.cover || '@/assets/icon/专辑默认.png'" 
            alt="封面"
            :class="{ 'rotating': playerStore.isPlaying }"
          >
        </div>
        <div class="song-info">
          <div class="song-name">{{ playerStore.currentSong?.songname || '暂无播放' }}</div>
          <div class="song-artist">{{ playerStore.currentSong?.singer?.[0]?.name || '未知歌手' }}</div>
        </div>
      </div>

      <!-- 进度条和时间戳 -->
      <div class="progress-container">
        <span class="time-stamp">{{ formatTime(playerStore.currentTime) }}</span>
        <div class="progress-bar" @click="seekToPosition">
          <div class="progress-bg"></div>
          <div class="progress-current" :style="{ width: progressPercentage + '%' }"></div>
          <div class="progress-dot" :style="{ left: progressPercentage + '%' }"></div>
        </div>
        <span class="time-stamp">{{ formatTime(playerStore.duration) }}</span>
      </div>

      <div class="player-controls">
        <div class="control-button play" @click="playerStore.togglePlay">
          <img v-if="playerStore.isPlaying" src="@/assets/icon/暂停.png" alt="暂停">
          <img v-else src="@/assets/icon/播放1.png" alt="播放">
        </div>
        <div class="control-button list">
          <img src="@/assets/icon/列表.png" alt="播放列表">
        </div>
      </div>
    </div>
    <audio
      ref="audioRef"
      :src="playerStore.currentSong?.url"
      crossorigin="anonymous"
      @timeupdate="onTimeUpdate"
      @ended="onEnded"
      @canplay="onCanPlay"
      @error="onError"
    ></audio>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, onBeforeMount, computed } from 'vue'
import { usePlayerStore } from '@/store'
import { useRoute, useRouter } from 'vue-router'
import { musicApi } from '@/api/music'

const playerStore = usePlayerStore()
const audioRef = ref(null)
const route = useRoute()
const router = useRouter()

// 计算进度百分比
const progressPercentage = computed(() => {
  if (!playerStore.duration) return 0;
  return (playerStore.currentTime / playerStore.duration) * 100;
});

// 格式化时间
const formatTime = (seconds) => {
  if (!seconds) return '00:00';
  const mins = Math.floor(seconds / 60);
  const secs = Math.floor(seconds % 60);
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
};

// 点击进度条跳转
const seekToPosition = (event) => {
  const progressBar = event.currentTarget;
  const rect = progressBar.getBoundingClientRect();
  const offsetX = event.clientX - rect.left;
  const percentage = offsetX / rect.width;
  
  if (playerStore.duration) {
    const newTime = percentage * playerStore.duration;
    playerStore.currentTime = newTime;
    
    // 更新音频元素的当前时间
    const audioElement = audioRef.value;
    if (audioElement) {
      audioElement.currentTime = newTime;
    }
  }
};

// 修改跳转到播放详情页的方法
const showPlayerDetail = () => {
  if (playerStore.currentSong?.songmid) {
    // 不使用路由跳转，而是通过状态控制详情页显示
    playerStore.setDetailShow(true)
  }
}

// 添加错误处理函数
const onError = (e) => {
  console.error('音频加载错误:', e)
  console.error('当前URL:', playerStore.currentSong?.url)
  
  // 获取更详细的错误信息
  if (audioRef.value && audioRef.value.error) {
    console.error('错误代码:', audioRef.value.error.code)
    console.error('错误信息:', audioRef.value.error.message)
  }
  
  // 检查是否有当前歌曲，如果没有则不重试
  if (playerStore.currentSong && playerStore.currentSong.songmid) {
    console.log('尝试重新获取歌曲URL')
    setTimeout(() => fetchSongData(playerStore.currentSong.songmid), 1000)
  }
}

// 修改 fetchSongData 方法中的错误处理
const fetchSongData = async (songId) => {
  console.log('尝试获取歌曲数据，songId:', songId)
  
  const targetSongId = songId || route.query.id
  
  if (!targetSongId) {
    console.log('无歌曲ID，跳过获取')
    return
  }

  try {
    // 先获取歌曲详细信息
    console.log('获取歌曲详细信息，songId:', targetSongId)
    const songDetailResponse = await musicApi.search({
      key: targetSongId,
      pageNo: 1,
      pageSize: 1,
      t: 0
    })
    
    console.log('歌曲详细信息响应:', songDetailResponse)
    
    // 从响应中提取歌曲信息
    const songDetail = songDetailResponse?.data?.data?.list?.[0]
    
    if (!songDetail) {
      console.warn('未找到歌曲详情，尝试使用备用方法')
    }
    
    // 获取歌曲URL
    console.log('正在请求歌曲URL，songId:', targetSongId)
    const response = await musicApi.getSongUrl(targetSongId)
    
    console.log('歌曲URL响应:', response)
    
    if (!response || !response.data) {
      throw new Error('获取歌曲URL失败')
    }
    
    // 检查是否有错误响应
    if (response.data.result === 400) {
      // console.error('获取播放链接出错:', response.data.errMsg || '未知错误')
      
      // 如果是VIP歌曲或版权问题，可以尝试使用备用歌曲
      if (songDetail) {
        console.log('尝试获取相似歌曲...')
        // 这里可以添加获取相似歌曲的逻辑
      }
      
      // 不要立即抛出错误，而是尝试使用默认歌曲
      console.log('尝试使用默认歌曲...')
      setTimeout(() => setDefaultSong(), 500)
      return // 提前返回，避免后续代码执行
    }

    // 处理URL，确保获取到的是字符串
    let songUrl = ''
    
    // 检查响应数据的结构
    if (typeof response.data === 'string') {
      songUrl = response.data
    } else if (response.data.url) {
      songUrl = response.data.url
    } else if (typeof response.data.data === 'string') {
      songUrl = response.data.data
    } else if (response.data.data && response.data.data.url) {
      songUrl = response.data.data.url
    }

    if (!songUrl) {
      console.error('无法从响应中提取URL:', response.data)
      
      // 如果是付费内容，可以显示提示
      if (response.data && response.data.result === 400) {
        console.warn('可能是VIP歌曲或版权受限')
        // 这里可以添加处理VIP歌曲的逻辑
      }
      
      throw new Error('歌曲URL为空')
    }

    // 确保URL是有效的HTTP(S)链接
    if (!songUrl.startsWith('http')) {
      songUrl = `https://${songUrl}`
    }

    console.log('解析后的歌曲URL:', songUrl)
    
    // 修复：确保有有效的albummid，否则使用默认封面
    const coverUrl = songDetail && songDetail.albummid 
      ? `https://y.qq.com/music/photo_new/T002R300x300M000${songDetail.albummid}.jpg` 
      : 'https://y.qq.com/mediastyle/global/img/album_300.png';
    
    // 更新播放器状态，使用从搜索结果获取的详细信息
    playerStore.currentSong = {
      songmid: targetSongId,
      songname: songDetail ? songDetail.songname : '正在播放',
      singer: songDetail ? songDetail.singer : [{ name: '未知歌手' }],
      cover: coverUrl,
      url: songUrl
    }

    console.log('更新后的歌曲信息:', playerStore.currentSong)

    // 预加载音频但不自动播放
    const audio = audioRef.value
    if (audio) {
      // 先暂停当前播放，避免播放被中断错误
      audio.pause()
      
      // 设置新的URL并加载
      audio.src = songUrl
      audio.load()
      
      // 不自动播放
      playerStore.isPlaying = false
    }
  } catch (error) {
    console.error('获取或加载歌曲失败:', error)
    playerStore.isPlaying = false
    
    // 显示错误提示
    if (error.message && (error.message.includes('VIP') || error.message.includes('版权'))) {
      // 这里可以添加VIP歌曲提示
      console.warn('该歌曲可能为VIP专享或版权受限')
    }
    
    // 如果获取失败，尝试播放默认歌曲
    console.log('尝试加载默认歌曲...')
    setTimeout(() => setDefaultSong(), 500)
  }
}

// 监听当前歌曲变化
watch(() => playerStore.currentSong, (newSong) => {
  // 移除自动播放逻辑
  // if (newSong && newSong.url) {
  //   // 当歌曲改变时，自动播放
  //   playerStore.isPlaying = true
  // }
})

// 监听路由变化
watch(() => route.query.id, (newId) => {
  if (newId) {
    fetchSongData()
  }
}, { immediate: true })

const onTimeUpdate = () => {
  if (audioRef.value) {
    playerStore.currentTime = audioRef.value.currentTime
    playerStore.duration = audioRef.value.duration
  }
}

const onEnded = () => {
  playerStore.playNext()
}

const onCanPlay = () => {
  if (playerStore.isPlaying) {
    audioRef.value?.play().catch(err => {
      console.error('播放失败:', err)
      playerStore.isPlaying = false
    })
  }
}

// 添加默认歌曲设置
const setDefaultSong = async () => {
  if (!playerStore.currentSong) {
    console.log('设置默认歌曲')
    
    try {
      // 获取歌曲URL
      const songId = '002ASCKm3ROw7t'
      const response = await musicApi.getSongUrl(songId)
      
      let songUrl = ''
      // 检查响应数据的结构
      if (typeof response.data === 'string') {
        songUrl = response.data
      } else if (response.data.url) {
        songUrl = response.data.url
      } else if (typeof response.data.data === 'string') {
        songUrl = response.data.data
      } else if (response.data.data && response.data.data.url) {
        songUrl = response.data.data.url
      }
      
      if (!songUrl) {
        throw new Error('歌曲URL为空')
      }
      
      // 确保URL是有效的HTTP(S)链接
      if (!songUrl.startsWith('http')) {
        songUrl = `https://${songUrl}`
      }
      
      // 直接设置正确的歌曲信息
      playerStore.currentSong = {
        songmid: songId,
        songname: '美人鱼', // 正确的歌曲名称
        singer: [{ name: '林俊杰' }], // 正确的歌手名称
        cover: 'https://y.qq.com/music/photo_new/T002R300x300M000002g6zv02X7SNi.jpg', // JJ陆专辑封面
        url: songUrl
      }
      
      console.log('设置默认歌曲信息:', playerStore.currentSong)
      
      // 不要自动播放，等待用户交互
      playerStore.isPlaying = false
    } catch (error) {
      console.error('设置默认歌曲失败:', error)
    }
  }
}

// 修改 onBeforeMount 钩子
onBeforeMount(() => {
  // 如果路由中有 id 参数则获取歌曲，否则设置默认歌曲
  if (route.query.id) {
    fetchSongData(route.query.id)
  } else {
    setDefaultSong()
  }
  
  // 确保不自动播放
  playerStore.isPlaying = false
})

onMounted(() => {
  console.log('组件已挂载，当前播放状态:', playerStore.isPlaying)
  console.log('当前歌曲:', playerStore.currentSong)
  
  if (playerStore.isPlaying && playerStore.currentSong?.url) {
    console.log('尝试播放音频')
    audioRef.value?.play().catch(err => {
      console.error('播放失败:', err)
      playerStore.isPlaying = false
    })
  }
})

// 修改播放状态监听
watch(() => playerStore.isPlaying, async (newValue) => {
  console.log('播放状态变化:', newValue)
  const audio = audioRef.value
  
  if (!audio) return
  
  if (newValue) {
    try {
      if (!playerStore.currentSong?.url) {
        throw new Error('播放失败: URL为空')
      }
      
      // 确保音频已加载
      if (audio.readyState < 2) {
        audio.load()
        // 等待音频可以播放
        await new Promise((resolve) => {
          const canPlayHandler = () => {
            audio.removeEventListener('canplaythrough', canPlayHandler)
            resolve()
          }
          audio.addEventListener('canplaythrough', canPlayHandler)
          
          // 设置超时，避免无限等待
          setTimeout(resolve, 3000)
        })
      }
      
      await audio.play()
      console.log('音频开始播放')
    } catch (err) {
      // console.error('播放失败:', err)
      playerStore.isPlaying = false
    }
  } else {
    audio.pause()
    console.log('音频已暂停')
  }
})

// 监听当前歌曲变化的逻辑
watch(() => playerStore.currentSong, async (newSong, oldSong) => {
  console.log('当前歌曲变化:', newSong)
  
  if (newSong && newSong.url) {
    const audio = audioRef.value
    if (audio) {
      // 先暂停当前播放，避免播放被中断错误
      audio.pause()
      
      // 设置新的URL并加载
      audio.src = newSong.url
      audio.load()
      
      // 如果 store 中的播放状态为播放，则播放新歌曲
      if (playerStore.isPlaying) {
        // 等待一小段时间再播放，避免播放冲突
        setTimeout(async () => {
          try {
            await audio.play()
            console.log('新歌曲开始播放')
          } catch (playError) {
            console.error('自动播放失败:', playError)
            playerStore.isPlaying = false
          }
        }, 100)
      }
    }
  }
})
</script>

<style lang="scss" scoped>
/* 添加旋转动画 */
@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.player {
  position: fixed;
  bottom: 50px; // TabBar 的高度
  left: 0;
  width: 100%;
  height: 50px; // 稍微增加高度
  background: linear-gradient(to right, #f8f9fa, #dba3a3, #c2cbd3); // 添加渐变背景
  box-shadow: 0 -1px 10px rgba(0, 0, 0, 0.08);
  z-index: 100;
  border-top: 1px solid rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  border-radius: 20px 20px 0 0;

  &:hover {
    box-shadow: 0 -2px 15px rgba(0, 0, 0, 0.12);
  }

  .player-content {
    height: 100%;
    padding: 0 15px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .player-info {
    flex: 0 0 auto;
    width: 30%; /* 减小歌曲信息区域的宽度 */
    display: flex;
    align-items: center;
    overflow: hidden;
    cursor: pointer;
    transition: transform 0.2s ease;

    &:hover {
      transform: translateX(3px);
    }

    .song-cover {
      width: 44px;
      height: 44px;
      border-radius: 6px;
      overflow: hidden;
      margin-right: 12px;
      flex-shrink: 0;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
      
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        transition: transform 0.3s ease;
        
        &.rotating {
          animation: rotate 8s linear infinite;
        }
      }

      &:hover img:not(.rotating) {
        transform: scale(1.05);
      }
    }

    .song-info {
      flex: 1;
      overflow: hidden;
      
      .song-name {
        font-size: 14px;
        font-weight: 600;
        margin-bottom: 4px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        color: #333;
      }
      
      .song-artist {
        font-size: 12px;
        color: #888;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }

  .progress-container {
    flex: 1.3; /* 增加进度条容器的比例 */
    display: flex;
    align-items: center;
    padding: 0px; /* 减小内边距，让进度条更长 */
    
    .time-stamp {
      font-size: 12px;
      color: #888;
      width: 40px;
      text-align: center;
      font-family: 'Roboto', sans-serif;
      letter-spacing: 0.5px;
    }
    
    .progress-bar {
      flex: 3; /* 进一步增加进度条的长度比例 */
      height: 4px;
      position: relative;
      cursor: pointer;
      margin: 0 5px; /* 减小外边距 */
      
      .progress-bg {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: #e9e9e9;
        border-radius: 4px;
      }
      
      .progress-current {
        position: absolute;
        top: 0;
        left: 0;
        height: 100%;
        background: linear-gradient(to right, #d3638a, #556ab0);
        border-radius: 4px;
        transition: width 0.1s linear;
      }
      
      .progress-dot {
        position: absolute;
        top: 50%;
        width: 10px;
        height: 10px;
        background-color: #fff;
        border: 2px solid #31c27c;
        border-radius: 50%;
        transform: translate(-50%, -50%);
        box-shadow: 0 0 4px rgba(0, 0, 0, 0.2);
        opacity: 0;
        transition: opacity 0.2s ease;
      }
      
      &:hover {
        height: 6px;
        
        .progress-bg, .progress-current {
          top: 0;
          height: 100%;
        }
        
        .progress-dot {
          opacity: 1;
        }
      }
    }
  }

  .player-controls {
    flex: 0 0 auto;
    display: flex;
    align-items: center;
    gap: 8px; /* 减小按钮之间的间距 */
    margin-left: auto; /* 让控制按钮靠右 */
    padding-right: 5px; /* 右侧添加一点内边距 */

    .control-button {
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      
      &.play {
        width: 42px;
        height: 42px;
        // background: linear-gradient(145deg, #f7f9f8, #f7f8f7);
        border-radius: 50%;
        transition: all 0.2s ease;
        // box-shadow: 0 3px 8px rgba(248, 250, 249, 0.3);
        
        img {
          width: 30px;
          height: 30px;
          filter: brightness(0); /* 将图标颜色改为黑色 */
        }
        
        &:active {
          transform: scale(0.95);
          box-shadow: 0 1px 4px rgba(189, 87, 87, 0.3);
        }
      }
      
      &.list {
        width: 34px;
        height: 34px;
        border-radius: 50%;
        background-color: rgba(0, 0, 0, 0.03);
        transition: all 0.2s ease;
        
        img {
          width: 22px;
          height: 22px;
          opacity: 0.7;
          transition: all 0.2s ease;
        }
        
        &:active {
          transform: scale(0.95);
        }
      }
      
      &:hover {
        &.play {
          background: linear-gradient(145deg, #2db370, #31c27c);
          box-shadow: 0 4px 12px rgba(49, 194, 124, 0.4);
          transform: translateY(-2px);
        }
        
        &.list {
          background-color: rgba(0, 0, 0, 0.06);
          
          img {
            opacity: 0.9;
          }
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .player {
    .progress-container {
      padding: 0 5px;
      
      .time-stamp {
        width: 35px;
        font-size: 11px;
      }
    }
    
    .player-info {
      width: 30%;
      
      .song-cover {
        width: 40px;
        height: 40px;
        border-radius: 20px;
      }
    }
  }
}
</style>